<template>
  <div
    style="
      margin: 20px 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    "
  >
    <h2 style="font-size: 16px; color: #e41a1a">场馆列表</h2>
    <el-link type="primary" @click="Jumphome">返回</el-link>
  </div>
  <div style="margin: 40px 40px">
    <el-row :gutter="20">
      <template v-for="item in positionList">
        <el-col :span="8" style="margin-bottom: 20px">
          <position-card :item="item"></position-card>
        </el-col>
      </template>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import PositionCard from "@/components/PositionCard.vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";

const positionList = ref([]);
const page = ref(1);
const loading = ref(false);
const route = useRoute();
const router = useRouter();

async function checkUser() {
  const res = await axios.get("http://localhost:8000/Login/check", {
    withCredentials: true,
  });
  const data = res.data;
  if (data.code == 0) {
    if (data.data.status == 1) {
      status.value = true;
      userInfo.value = data.data.userInfo;
      userID.value = userInfo.value.userID;
      emit('updateUserID', userID.value);
    }
  } else {
    ElMessage({
      message: data.msg,
      type: "error",
    });
  }
}

function Jumphome() {
  router.push({ name: "home" });
}

onMounted(async () => {
  await searchYard();
});

watch(
  () => route.query.query,
  async (newQuery, oldQuery) => {
    if (newQuery !== oldQuery) {
      page.value = 1;
      positionList.value = [];
      await searchYard();
    }
  }
);

const searchYard = async (limit = 10, append = false) => {
  loading.value = true;
  try {
    const res = await axios.get(`http://localhost:8000/Search/searchYard`, {
      params: {
        query: route.query.query,
        page: page.value,
        limit: limit,
      },
    });
    if (append) {
      positionList.value = positionList.value.concat(res.data);
    } else {
      positionList.value = res.data;
    }
    page.value = page.value + 1;
  } catch (error) {
    console.error("Error fetching yard list:", error);
  } finally {
    // end loading
    loading.value = false;
  }
};
</script>

<style scoped>
.el-link {
  margin-right: 8px;
}
.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
</style>
